package cn.com.git.admin.config.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsUtils;

/**
 * spring security 配置
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {



    @Override
    public void configure(WebSecurity web) throws Exception {
        //设置不拦截 swagger 相关请求
        web.ignoring().antMatchers("/swagger-ui.html");
        web.ignoring().antMatchers("/webjars/**");
        web.ignoring().antMatchers("/favicon.ico");
        web.ignoring().antMatchers("/swagger-resources/**");
        web.ignoring().antMatchers("/v2/api-docs");
        web.ignoring().antMatchers("/upms/sso/**/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //设置拦截结果 权限配置
        http
                .authorizeRequests()
                .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                .anyRequest().authenticated();

        //禁用退出处理
        http.logout().disable();
        //自定义无权限处理 未登录异常处理
        http.exceptionHandling()
                .authenticationEntryPoint(unauthorizedEntryPoint())
                .accessDeniedHandler(deniedHandler());

        //session 无状态
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.cors().and().csrf().disable();
        //添加权限校验的过滤器
        http.addFilterBefore(deniedAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }


    @Bean
    public AuthenticationFilter deniedAuthenticationFilter() throws Exception {
        return new AuthenticationFilter(authenticationManager());
    }

    @Bean
    public AccessDeniedHandler deniedHandler() {
        return new AccessDeniedHandler();
    }

    @Bean
    public UnauthorizedEntryPoint unauthorizedEntryPoint() {
        return new UnauthorizedEntryPoint();
    }

    @Bean
    public SessionRegistry registry() {
        return new SessionRegistryImpl();
    }

}
